package com.mrobuy.util;

public class CodeEncoder {

    private static char add(char c, int offset) {

        int value = c;

        if ( c <= 57 && c >= 48 ) {
            value -= 48;
            value += offset;
            if ( value > 9 ) {
                value -= 10;
            }
            value+=48;
        } else if ( c <= 90 && c >= 65  ) {
            value -= 65;
            value += offset;
            if ( value > 25 ) {
                value -= 26;
            }
            value+=65;
        }  else if ( c <= 122 && c >= 97  ) {
            value -= 97;
            value += offset;
            if ( value > 25 ) {
                value -= 26;
            }
            value+=97;
        }

        return (char)value;
    }

    private static char sub(char c, int offset) {

        int value = c;

        if ( c <= 57 && c >= 48 ) {
            value -= 48;
            value -= offset;
            if ( value < 0 ) {
                value += 10;
            }
            value+=48;
        } else if ( c <= 90 && c >= 65  ) {
            value -= 65;
            value -= offset;
            if ( value < 0 ) {
                value += 26;
            }
            value+=65;
        }  else if ( c <= 122 && c >= 97  ) {
            value -= 97;
            value -= offset;
            if ( value < 0 ) {
                value += 26;
            }
            value+=97;
        }


        return (char)value;
    }



    public static String encode(String code, int seed) {
        if (isBlank(code)) {
            return "";
        }

        StringBuffer buffer = new StringBuffer(String.valueOf(seed));

        String plan = code.trim();

        for (char c : plan.toCharArray()) {
            buffer.append(add(c, seed));
        }


        buffer.append(code.substring(code.length()-3));

        return buffer.toString();
    }



    public static String decoder(String code) {
        if (isBlank(code)) {
            return "";
        }

        char seed = code.charAt(0);

        StringBuffer buffer = new StringBuffer();

        String plan = code.trim();

        for (int i = 1; i < plan.toCharArray().length -3; i++) {

            char c = plan.toCharArray()[i];
            buffer.append(sub(c, seed-48));
        }


        return buffer.toString();
    }

    private static boolean isBlank(String value) {
        if ( value==null ) {
            return true;
        }
        return value.trim().length()==0;
    }


    public static void main(String[] args) {


        System.out.println(encode("5F0093", "327014".hashCode()%9 + 1));


    }
}
